In this project, the open-source R programming language is used to model the progression in the COVID-19 pandemic in different U.S. counties. R is maintained by an international team of developers who make the language available at The Comprehensive R Archive Network. Readers interested in reusing our code and reproducing our results should have R installed locally on their machines. R can be installed on a number of different operating systems (see Windows, Mac, and Linux for the installation instructions for these systems). We also recommend using the RStudio interface for R. The reader can download RStudio for free by following the instructions at the link. For non-R users, we recommend the Hands-on Programming with R for a brief overview of the software’s functionality. Hereafter, we assume that the reader has an introductory understanding of the R programming language.
In the code chunk below, we load the packages used to support our analysis. Note that the code of this and any of the code chunks can be hidden by clicking on the ‘Hide’ button to facilitate the navigation. The reader can hide all code and/or download the Rmd file associated with this document by clicking on the Code button on the top right corner of this document. Our input and output files can also be accessed/ downloaded from fmegahed/covid19.
if(require(pacman)==FALSE) install.packages("pacman") # check to see if the pacman package is installed; if not install it
if(require(devtools)==FALSE) install.packages("devtools") # check to see if the devtools package is installed; if not install it
# to check and install if these packages are not found locally on machine
if(require(albersusa)==FALSE) devtools::install_github('hrbrmstr/albersusa') #install package if needed
if(require(albersusa)==FALSE) devtools::install_github('dreamRs/r2d3maps') #install package if needed
# check if packages are not installed; if yes, install missing packages
pacman::p_load(tidyverse, magrittr, janitor, dataPreparation, lubridate, skimr, # for data analysis
COVID19, rvest, readxl, # for extracting relevant data
DT, pander, stargazer, knitr, # for formatting and nicely printed outputs
scales, RColorBrewer, DataExplorer, tiff, grid,# for plots
plotly, albersusa, tigris, leaflet, tmap, # for maps
zoo, fpp2, NbClust, # for TS analysis and clustering
VIM, rgdal, spdep, nimble, fastDummies, matrixStats, # for spatial regression
nnet, caret, # for multinomial regression modeling
conflicted) # for managing conflicts in functions with same names
# Handling conflicting function names from packages
conflict_prefer('combine', 'dplyr') # Preferring dplyr::combine over any other package
conflict_prefer('select', "dplyr") #Preferring dplyr::select over any other package
conflict_prefer("summarize", "dplyr") # similar to above but with dplyr::summarize
conflict_prefer("filter", "dplyr") # Preferring filter from dplyr
conflict_prefer("dist", "stats") # Preferring dist from stats
conflict_prefer("as.dist", "stats") # Preferring as.dist from stats
# Custom Functions
source_url('https://raw.githubusercontent.com/fmegahed/covid19-deaths/master/Markdown/custom_functions.R')
set.seed(2020) # to assist with reproducibility
sInfo = sessionInfo() # saving all the packages/functions & session info
For our analysis, we fuse data from multiple sources. We describe the process of obtaining and merging each of these sources in the subsections below.
In this section, we utilize the COVID19 package to obtain the following information: (Guidotti & Ardia, 2020)
From this information, we have also computed the new daily and weekly confirmed cases/deaths per county. The data is stored in a tidy format, but can be expanded to a wide format using pivot_wider() from the tidyverse package.
endDate = '2021-01-02'
endDatePrintV = format(ymd(endDate), format = "%b %d, %Y")
counties = covid19(country = "US",
level = 3, # for county
start = "2020-03-01", # First Sunday in March
end = endDate, # end Date
raw = FALSE, # to ensure that all counties have the same grid of dates
amr = NULL, # we are not using the apple mobility data for our analysis
gmr = NULL, # we are not using the Google mobility data for our analysis
wb = NULL, # world bank data not helpful for county level analysis
verbose = FALSE)
counties %<>% # next line removes non-contiguous US states/territories
filter(!administrative_area_level_2 %in% c('Alaska', 'Hawaii', 'Puerto Rico', 'Northern Mariana Islands', 'Virgin Islands')) %>%
fast_filter_variables(verbose = FALSE) %>% #dropping invariant columns or bijections
filter(!is.na(key_numeric)) %>% # these are not counties
group_by(id) %>% # grouping the data by the id column to make computations correct
arrange(id, date) %>% # to ensure correct calculations
mutate(day = wday(date, label = TRUE) %>% factor(ordered = F), # day of week
newCases = c(NA, diff(confirmed)), # computing new daily cases per county
newDeaths = c(NA, diff(deaths)) ) # computing new daily deaths per county
# manually identifying factor variables
factorVars = c("school_closing", "workplace_closing", "cancel_events",
"gatherings_restrictions", "transport_closing", "stay_home_restrictions",
"internal_movement_restrictions", "international_movement_restrictions",
"information_campaigns", "testing_policy", "contact_tracing")
counties %<>% # converting those variables into character and then factor
mutate_at(.vars = vars(any_of(factorVars)), .funs = as.character) %>%
mutate_at(.vars = vars(any_of(factorVars)), .funs = as.factor)
# Saving the data into an RDS file
saveRDS(counties, paste0("../Data/counties.rds"))
In the code chunk below, we obtain seven additional datasets, whose variables can explain the differences between the time-series of the number of COVID cases per county:
A. Rural/ Underserved Counties: From the Consumer Financial Protection Bureau, we have obtained the Final 2020 List titled: Rural or underserved counties. Per the website, the procedure for determining the classification of a county is as follows: “Beginning in 2020, the rural or underserved counties lists use a methodology for identifying underserved counties described in the Bureau’s interpretive rule: Truth in Lending Act (Regulation Z); Determining “Underserved” Areas Using Home Mortgage Disclosure Act Data.”
B. Based on the US Census Data, we extracted the land area in square miles for each county, which we combined with population to compute each county’s population density, which we hypothesize to be predictive of hotspots for COVID transmission based on the available COVID-19 literature.
C. Based on the MIT Election Data and Science Lab (2018), we have obtained the voting results for all counties in the 2016 Presidential elections. The data was used to compute the percentage of total votes that went to President Trump, with the underlying hypothesis that the politicization of COVID response (e.g., perception/willingness to use face masks, policies and the population’s reaction to the disease) may be explained by party affiliation.
D. We extracted an overall government response index capturing the strength of COVID-19 response policies on a state (and the District of Columbia) level from the Blavatnik School of Government’s GitHub Repository. This index captures 13 different indicators, capturing the ``full range of government response’’. Details for how this indicator is computed can be found at BSG-WP-2020/034.
E. Based on the following Kaiser Health News Webpage, we extracted by county information on the percent of population aged 60+ and the number of ICU beds per Seniors.
F. We have engineered a region variable based on the CDC’s 10 Regions Framework. While geographic regions are hypothesized to be a factor in disease outbreaks, we chose to utilize the CDC regions specifically based on the following explanation from the aforementioned link:
> “CDC’s National Center for Chronic Disease Prevention and Health Promotion (NCCDPHP) is strengthening the consistency and quality of the guidance, communications, and technical assistance provided to states to improve coordination across our state programs”
G. Based on the Census’s Small Area Income and Poverty Estimates (SAIPE) Program, we extracted the estimate for the percent of population in poverty. The estimate is based on 2018 data (released in December 2019). At the time of the start of our analysis, these estimates were the most up to date publicly available data.
crossSectionalData = counties %>% ungroup() %>%
select(id, key_numeric, key_google_mobility, population,
administrative_area_level_2, administrative_area_level_3) %>%
unique()
# [A] Rural or Urban Classification of the County
ru = read.csv("https://www.consumerfinance.gov/documents/8911/cfpb_rural-underserved-list_2020.csv")
ru %<>% transmute(key_numeric = FIPS.Code, #renaming FIPS.Code to key_numeric
countyType = "Rural/Underserved") # creates two vars and drop old vars
crossSectionalData = merge(crossSectionalData, ru, by = "key_numeric", all.x = TRUE) # to define NA counties
crossSectionalData$countyType %<>% replace_na("Other") # for any county not in the Consumer FIN data replace NA by Other
# [B] Population Density of Each County
download.file("https://www2.census.gov/library/publications/2011/compendia/usa-counties/excel/LND01.xls",
destfile = "../Data/LND01.xls", mode = "wb") # downloading Land Area Data Per the 2010 Census
areas = read_excel("../Data/LND01.xls") %>% # reading the Excel file
select(STCOU, LND110210D) #selecting only the FIPS and the Land Area from the 2010 Census variables
colnames(areas) = c("key_numeric", "LandAreaSqMiles2010") # Renaming the columns
areas$key_numeric %<>% as.numeric() # to remove leading 0
crossSectionalData = merge(crossSectionalData, areas, by ="key_numeric", all.x = TRUE) # adding the area to data frame
crossSectionalData$popDensity = crossSectionalData$population / crossSectionalData$LandAreaSqMiles2010 # creating the population density variable
crossSectionalData %<>% select(-c(population, LandAreaSqMiles2010)) #dropping two variables used in creating pop density
# [C] 2016 Presidential Elections County Data from Harvard https://doi.org/10.7910/DVN/VOQCHQ
elections = read.csv("../Data/countypres_2000-2016.csv") %>% # reading the downloaded CSV
filter(year == 2016 & party == "republican") %>% # just keeping data for recent election and republican votes
mutate(key_numeric = FIPS, # renaming FIPS to key_numeric
percRepVotes = 100*(candidatevotes/totalvotes) ) %>% # computing percent of republican votes (from total votes)
select(key_numeric, percRepVotes) # keeping only the key and variable used in merge
crossSectionalData %<>% merge(elections, by = "key_numeric", all.x = TRUE) # merge with the counties data
# [D] Policy Data
policy = read_csv('https://raw.githubusercontent.com/OxCGRT/USA-covid-policy/master/data/OxCGRT_US_latest.csv')
policy = filter(policy, !is.na(RegionName) | !RegionName %in% c('Alaska', 'Hawaii'))
policy$state = toupper(policy$RegionName) # a state variable = an upper case of existing RegionName
policy$Date %<>% ymd() # converting the Date data to a date format
policySummary = policy %>% # calculating a summary table of median value for the GovernmentResponseIndex per state
filter(Date >= '2020-03-01' & Date <= endDate) %>% # to match our COVID Data timeSeries
group_by(state) %>% # perform computations using the median value, per state, for each index
summarise(GovernmentResponseIndexMedian = median(GovernmentResponseIndex, na.rm = TRUE))
policySummary$state %<>% str_replace('WASHINGTON DC', 'DISTRICT OF COLUMBIA') %>% str_to_title()
crossSectionalData %<>% merge(policySummary, by.x = "administrative_area_level_2", by.y = 'state', all.x = TRUE)
# [E] Kaiser Health News Data on the County Level
hospitals = read.csv("../Data/data-FPBfZ.csv") %>% # downloaded from KHN on 2020-10-26 (~9:30 pm EDT)
transmute(State = State, # keeping the State Variable | transmute drops variables that are not in call
County = County, # keeping the County Variable
PercentSeniors = Percent.of.Population.Aged.60., # Shortening Original Variable Name
icuBedsPer10000Seniors = 10000 * ICU.Beds/Population.Aged.60.) # Computing icuBedsPer10000Seniors
crossSectionalData %<>% merge(hospitals,
by.x = c("administrative_area_level_2", "administrative_area_level_3"),
by.y = c("State", "County"), all.x = TRUE)
# [F] CDC Regions for Each State
regionsCDC = data.frame(States = c('Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island' ,
'Vermont', 'New York', # End of Region A
'Delaware', 'District of Columbia', 'Maryland', 'Pennsylvania',
'Virginia', 'West Virginia', 'New Jersey', # End of Region B
'North Carolina', 'South Carolina', 'Georgia', 'Florida', # Region C
'Kentucky', 'Tennessee', 'Alabama', 'Mississippi', # Region D
'Illinois', 'Indiana', 'Michigan', 'Minnesota', 'Ohio',
'Wisconsin', # End of Region E
'Arkansas', 'Louisiana', 'New Mexico', 'Oklahoma', 'Texas', # Region F
'Iowa', 'Kansas', 'Missouri', 'Nebraska', # Region G
'Colorado', 'Montana', 'North Dakota', 'South Dakota',
'Utah', 'Wyoming', # End of Region H
'Arizona', 'California', 'Hawaii', 'Nevada', # Region I
'Alaska', 'Idaho', 'Oregon', 'Washington' # Region J
),
regions = c(rep('A', 7), rep('B', 7), rep('C', 4),
rep('D', 4), rep('E', 6), rep('F', 5),
rep('G', 4), rep('H', 6), rep('I', 4),
rep('J', 4) ) )
crossSectionalData %<>% merge(regionsCDC, by.x = 'administrative_area_level_2', by.y = 'States', all.x = TRUE) # merge
# [G] Poverty Estimates
download.file("https://www2.census.gov/programs-surveys/saipe/datasets/2018/2018-state-and-county/est18all.xls",
destfile = "../Data/est18all.xls", mode = "wb") # downloading the data for poverty estimates (latest 2018)
poverty = read_excel("../Data/est18all.xls", skip = 3) %>% # reading the data in R
transmute(key_numeric = paste0(`State FIPS Code`, `County FIPS Code`) %>% as.numeric, # creating the key from two variables
povertyPercent = as.numeric(`Poverty Percent, All Ages`) ) # shortening povertyPercent Variable's Name
crossSectionalData %<>% merge(poverty, by = "key_numeric", all.x = TRUE) # merge
# Final Transformations before Saving the Counties Data
crossSectionalData %<>% mutate_at(.vars = c('countyType', 'regions'), as.factor) # converting the two vars to factor
# Saving the data into an RDS file
saveRDS(crossSectionalData, paste0("../Data/crossSectionalData.rds"))
# Tabulating the results and providing a way to export the table to different formats
datatable(crossSectionalData %>% select(-c(id, key_numeric, administrative_area_level_2, administrative_area_level_3)),
extensions = c('FixedColumns', 'Buttons'), options = list(
dom = 'Bfrtip',
scrollX = TRUE,
buttons = c('copy', 'csv', 'excel', 'pdf'),
fixedColumns = list(leftColumns = 1)),
rownames = FALSE) %>%
formatRound(columns= c('popDensity', 'percRepVotes', 'GovernmentResponseIndexMedian',
'PercentSeniors', 'icuBedsPer10000Seniors', 'povertyPercent'),
digits=1)
In this section, we perform an exploratory analysis on the data obtained from the multiple sources.
noGoogleNAs = filter(crossSectionalData, !is.na(key_google_mobility)) # removing NAs from key_google_mobility
idIndex = sample(noGoogleNAs$id, 9) # sampling 9 counties by id
# Saving cumulative deaths figure to an tiff file
tiff(filename = '../Figures/sampleCumulativeCases.tiff',
width = 1366, height =768, pointsize = 16)
counties %>% filter(id %in% idIndex) %>%
ggplot(aes(x = date, y = confirmed, group = id, color = key_google_mobility)) +
geom_line(size = 1.25) +
scale_x_date(date_breaks = "1 month", date_labels = "%b") +
facet_wrap(~ key_google_mobility, scales = 'free_y', ncol = 3) +
theme(legend.position = 'none') +
labs(color = '', x = 'Month', y = 'Cumulative Cases By County',
caption = paste0('Based on Data from March 01, 2020 - ', endDatePrintV)) +
scale_color_brewer(type = 'qual', palette = 'Paired')
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Creating an interactive plot for the markdown
p = ggplot2::last_plot() + geom_line(size = 0.75) + # modifying the plot for plotly
theme_bw(base_size = 9) + theme(legend.position = 'none') # to make margins smaller
ggplotly(p, height = 768) %>% layout_ggplotly()
# Saving new daily cases figure to an tiff file
tiff(filename = '../Figures/sampleNewDailyCases.tiff',
width = 1366, height =768, pointsize = 16)
counties %>% filter(id %in% idIndex) %>%
ggplot(aes(x = date, y = newCases, group = id, color = key_google_mobility)) +
geom_line(size = 1.25) +
scale_x_date(date_breaks = "1 month", date_labels = "%b") +
facet_wrap(~ key_google_mobility, scales = 'free_y', ncol = 3) +
theme(legend.position = 'none') +
labs(color = '', x = 'Month', y = 'New Daily Cases By County',
caption = paste0('Based on Data from March 01, 2020 - ', endDatePrintV)) +
scale_color_brewer(type = 'qual', palette = 'Paired')
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Creating an interactive plot for the markdown
p = ggplot2::last_plot() + geom_line(size = 0.75) + # modifying the plot for plotly
theme_bw(base_size = 9) + theme(legend.position = 'none') # to make margins smaller
ggplotly(p, height = 768) %>% layout_ggplotly()
crossSectionalData$fips = str_pad(crossSectionalData$key_numeric,
width = 5, side = 'left', pad = '0')
# Retrieving the U.S. county composite map as a simplefeature
cty_sf = counties_sf("aeqd") %>% filter(!state %in% c('Alaska', 'Hawaii')) # from albersua
cty_sf %<>% geo_join(crossSectionalData, by_sp= 'fips', by_df= 'fips')
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/countyTypes.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(cty_sf) + tm_polygons('countyType', title = 'County Type', palette = "Paired")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(cty_sf) + tm_polygons('countyType', title = 'County Type', palette = "Paired")
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/popDensity.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(cty_sf) + tm_polygons('popDensity', title = 'Population Density', palette = "Greens",
style = 'quantile')
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(cty_sf) + tm_polygons('popDensity', title = 'Population Density', palette = "Greens",
style = 'quantile')
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/repVotes.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(cty_sf) + tm_polygons('percRepVotes', title = '% Republican Votes', palette = "Reds")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(cty_sf) + tm_polygons('percRepVotes', title = '% Republican Votes', palette = "Reds")
state_sf = usa_sf("aeqd") %>% filter(!name %in% c('Alaska', 'Hawaii')) # from albersua
state_sf %<>% geo_join(crossSectionalData, by_sp= 'name', by_df= 'administrative_area_level_2')
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/govResponse.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(state_sf) + tm_polygons('GovernmentResponseIndexMedian',
title = 'Median Value of the Government Response Index', palette = "-Greens")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(state_sf) + tm_polygons('GovernmentResponseIndexMedian',
title = 'Median Value of the Government Response Index', palette = "-Greens")
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/percSeniors.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(cty_sf) + tm_polygons('PercentSeniors', title = '% Seniors', palette = "Greens")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(cty_sf) + tm_polygons('PercentSeniors', title = '% Seniors', palette = "Greens")
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/cdcRegions.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(state_sf) + tm_polygons('regions', title = 'CDC Region', palette = "Paired")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(state_sf) + tm_polygons('regions', title = 'CDC Region', palette = "Paired")
# Saving a higher quality tiff file for use in the paper
tiff(filename = '../Figures/povertyPercent.tiff', width = 1366, height =768, pointsize = 16)
tm_shape(cty_sf) + tm_polygons('povertyPercent', title = 'Poverty Percent', palette = "Greens")
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing the png output in the Markdown doc
tm_shape(cty_sf) + tm_polygons('povertyPercent', title = 'Poverty Percent', palette = "Greens")
It is important to note that, in our estimation, there are three important decisions to be made when performing time-series clustering:
Preparation of the Different Time-Series to be Clustered In this section, we have (a) selected the new daily cases per county as the primary variable of interest, (b) smoothed that variable using a seven-day moving average, and (c) scaled the observations within each county’s 7-day MA of new daily deaths such that it is bounded between 0 and 1. This allows us to compare the shape of the time-series/profile across counties of different populations and where the magnitude of the cases is quite different.
Choice of Distance Measure: The Euclidean distance, The Euclidean Distance i.e., the \(l_2\) norm, is the most commonly used distance measure since it is computationally efficient. However, it may not be suitable for applications where the time-series are of different length in addition to being sensitive to noise, scale and time shifts (Sardá-Espinosa, 2017).
Choice of Clustering Algorithm: A large number of clustering algorithms have been proposed in the literature. Most common clustering approaches are shape-based, which include \(k-\)means clustering and hierarchical clustering. The reader is referred to Aghabozorgi et al. (2015) for a detailed review. In our preliminary analysis, we have chosen to use the hierarchical clustering approach since it provides an easy to understand dendogram and the number of counties was small. However, in our full analysis, we will use the \(k-\)means clustering algorithm since it is computationally efficient. Furthermore, we overcame the traditional limitation of having to pre-specify \(k\) by utilizing 26 indexes for determining the optimal number of clusters in a data set based on the excellent approach and package implementation of Charrad et al. (2014).
clusteringPrep = counties %>% # from the counties
select(id, date, key_google_mobility, newCases) %>% # selecting minimal amount of cols for visual inspection
arrange(id, date) %>% # arranged to ensure correct calculations
mutate(newMA7 = rollmedianr(newCases, k = 7, fill = NA), # 7-day ma of new (adjusted) cases
maxMA7 = max(newMA7, na.rm = T), # obtaining the max per county to scale data
scaledNewMA7 = pmax(0, newMA7/maxMA7, na.rm = TRUE) ) %>% # scaling data to a 0-1 scale by county
select(id, key_google_mobility, date, scaledNewMA7) %>% # dropping the variable newCases
pivot_wider(names_from = date, values_from = scaledNewMA7) # converting the data to a wide format for clustering
constantColumns = which_are_constant(clusteringPrep, verbose = F) # identifying constant columns
datesDropped = colnames(clusteringPrep)[constantColumns] # used for printing the names after the code chunk
clusteringPrep %<>% select(-all_of(constantColumns) ) %>% # speeds up clustering by dec length of series
as.data.frame() # data needs to be data frame for clustering
row.names(clusteringPrep) = clusteringPrep[,1] # needed for tsclust
clusteringPrep = clusteringPrep[,-1] # dropping the id column since it is now row.name
The following dates were removed from our data frame since the scaledNEWMA7 variable was constant across all counties: 2020-03-01, 2020-03-02, 2020-03-03, 2020-03-04, 2020-03-05, 2020-03-06 and 2020-03-07.
clusteringPrep %<>% select(-c(key_google_mobility)) # removing this variable so we can cluster
nc = NbClust(clusteringPrep, distance = "euclidean", # euclidean distance
min.nc = 2, max.nc = 49, # searching for optimal k between k=2 and k=49
method = "kmeans", # using the k-means method
index = "all") # using 26 of the 30 indices in the package
## *** : The Hubert index is a graphical method of determining the number of clusters.
## In the plot of Hubert index, we seek a significant knee that corresponds to a
## significant increase of the value of the measure i.e the significant peak in Hubert
## index second differences plot.
##
## *** : The D index is a graphical method of determining the number of clusters.
## In the plot of D index, we seek a significant knee (the significant peak in Dindex
## second differences plot) that corresponds to a significant increase of the value of
## the measure.
##
## *******************************************************************
## * Among all indices:
## * 2 proposed 2 as the best number of clusters
## * 12 proposed 3 as the best number of clusters
## * 5 proposed 4 as the best number of clusters
## * 1 proposed 24 as the best number of clusters
## * 1 proposed 39 as the best number of clusters
## * 2 proposed 48 as the best number of clusters
##
## ***** Conclusion *****
##
## * According to the majority rule, the best number of clusters is 3
##
##
## *******************************************************************
kclus = nc$Best.partition %>% as.data.frame() %>% #obtaining the best partition/ cluster assignment for optimal k
rename(., cluster_group = .) %>% rownames_to_column("County")
#converting the wide to tall data and adding the cluster groupings
clusters = clusteringPrep %>%
rownames_to_column(var = "County") %>%
pivot_longer(cols = starts_with("2020"), names_to = "Date") %>%
inner_join(., kclus, by = "County") %>%
mutate(cluster_group = as.factor(cluster_group))
idClusters = clusters %>% select(c(County, cluster_group)) # creating a look-up table of county and cluster group
colnames(idClusters) = c('id', 'cluster_group') # renaming the columns
idClusters %<>% unique() #removing the duplicates due to different dates (we had that to ensure that the clustering was applied correctly)
# Adding Cluster Grouping to a subset of the counties data frame
clusterCounties = counties %>%
select(c(id, key_numeric, key_google_mobility, administrative_area_level_2, administrative_area_level_3)) %>%
inner_join(., idClusters, by ='id') %>%
mutate(cluster_group = paste0('C', cluster_group)) %>%
unique()
# saving the results as a RDS File
saveRDS(clusterCounties, '../Data/clusterCounties.rds')
In this subsection, we provide three plots:
spaghettiDF = counties %>% # from the counties
select(id, date, newCases, key_google_mobility) %>% # selecting minimal columns
left_join(clusterCounties[, c('id', 'cluster_group')], by = 'id') %>% # to get clusters
arrange(id, date) %>% # arranged to ensure correct calculations
mutate(newMA7 = rollmedianr(newCases, k = 7, fill = NA), # 7-day ma of new (adjusted) deaths
maxMA7 = max(newMA7, na.rm = T), # obtaining the max per county to scale data
scaledNewMA7 = pmax(0, newMA7/maxMA7, na.rm = TRUE) ) %>%
ungroup() %>% select(date, cluster_group, scaledNewMA7, key_google_mobility) %>%
group_by(date, cluster_group)
spaghettiDF$cluster_group %<>% as.factor()
# Creating a Named Color Scale
colorPal = brewer.pal(n= levels(spaghettiDF$cluster_group) %>% length(), 'Set2')
names(colorPal) = levels(spaghettiDF$cluster_group)
# Saving spaghetti plot to an tiff file
tiff(filename = '../Figures/spaghettiPlot.tiff', width = 1366, height =768, pointsize = 16)
spaghettiDF %>%
ggplot(aes(x = date, y = scaledNewMA7, color = cluster_group, group = key_google_mobility)) +
scale_x_date(date_breaks = "1 month", date_labels = "%b") +
geom_line(size = 0.25, alpha = 0.1) +
stat_summary(aes(group = 1),
fun= median,
geom = "line",
size = 1.25, col = 'black') +
facet_wrap(~ cluster_group, ncol = 1) +
theme(legend.position = 'none') +
labs(x = 'Month', y = 'Scaled New Cases By Cluster By Day',
caption = paste0('Solid black line represents the median for each cluster |
Based on Data from March 01, 2020 - ', endDatePrintV) ) +
scale_color_manual(values = colorPal)
invisible( dev.off() ) # to suppress the unwanted output from dev.off
# Printing a png version of the plot in Markdown (lower quality image for quicker compilation of HTML)
readTIFF("../Figures/spaghettiPlot.tiff") %>% grid.raster()